﻿using Qy.Core;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class AppLinkService : QyRepository<AppLink>
{
    public AppLinkService(ApplicationContext applicationContext) : base(applicationContext) { }
    public async Task<PagedInfo<ViewAppLink>> GetPageListAsync(QueryAppLink parm)
    {
        var exp = Expressionable.Create<AppLink>();
        exp = exp.AndIF(parm.Status, data => data.Status == parm.Status);
        exp = exp.AndIF(parm.Cid > 0, data => data.Cid == parm.Cid);

        return await Queryable()
            .LeftJoin<AppLinkCate>((data, cat) => data.Cid == cat.Id)
            .Where(exp.ToExpression())
            .WhereIF(!string.IsNullOrEmpty(parm.Name), (data, cat) => data.Name.Contains(parm.Name))
            .OrderBy((data) => data.Id, OrderByType.Desc)
            .Select((data, cat) => new ViewAppLink()
            {
                CateName = cat.CateName,
                Id = data.Id.SelectAll()
            })
            .ToPageAsync(parm);
    }

    public async Task<ViewAppLink> GetEditAsync(int id)
    {
        return await Queryable()
               .LeftJoin<AppLinkCate>((data, cat) => data.Cid == cat.Id)
               .Select((data, cat) => new ViewAppLink()
               {
                   CateName = cat.CateName
               }, true)
               .FirstAsync(data => data.Id == id);
    }

    public async Task<IEnumerable<AppLink>> GetListAsync(QueryAppLink query)
    {
        IEnumerable<AppLink> appLinks = await GetAllListAsync("Id desc");
        if (query.Cid > 0)
            return appLinks.Where(o => o.Cid == query.Cid && o.Status == true).Take(query.PageSize);
        else
            return appLinks.Take(query.PageSize);
    }

    public async Task<AppLink> GetOneAsync(QueryAppLink query)
    {
        IEnumerable<AppLink> appLinks = await GetAllListAsync("Id desc");
        return appLinks.FirstOrDefault(o => o.Cid == query.Cid && o.Status == true);
    }
}
